package com.bst.bsj.bops.web.controller;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.bst.bsj.base.controller.WebBaseController;
import com.bst.bsj.bops.BopsConstants;
import com.bst.bsj.bops.web.biz.PictureService;
import com.bst.bsj.common.dal.dataobject.Picture;
import com.bst.bsj.portal.yun.service.FolderItem;
import com.bst.bsj.portal.yun.service.ImageYunService;
import com.homewaimai.common.lang.StringUtil;
import com.homewaimai.framework.web.request.session.LoginUser;

@Scope("prototype")
@Controller
@RequestMapping("/sys/ueditor")
public class UeditorImageUploadController extends WebBaseController {

  @Autowired
  private ImageYunService imageYunService;

  @Autowired
  private PictureService pictureService;

  @RequestMapping(value = "/manage")
  public void ueditorManage(HttpServletRequest request, HttpServletResponse response) throws Exception {

    LoginUser loginUser = getLoginUser(request);
    String mid = loginUser.getMemberId();
    String subImgDir = mid;

    response.setContentType("text/html;charset=utf-8");
    StringBuffer buff = new StringBuffer();
    List<FolderItem> list = imageYunService.readDir(BopsConstants.IMG_MANAGER_PRE_ROOT_URL + subImgDir + "/");

    if (null != list) {
      for (FolderItem folderItem : list) {
        if ("file".equals(folderItem.type) || "File".equals(folderItem.type)) {
          buff.append("").append(folderItem.name).append("ue_separate_ue");
        }
      }
    }

    String result = "";
    if (buff.length() > 0) {
      result = buff.substring(0, buff.lastIndexOf("ue_separate_ue")).replace(File.separator, "/").trim();
    }
    try {
      response.getWriter().write(result);
      response.getWriter().flush();
      response.getWriter().close();
    } catch (Exception e) {
      logger.error("UeditorImageUploadAction error", e);
    }
  }

  @RequestMapping(value = "/upload")
  public void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html;charset=utf-8");
    Map<String, Object> params = getBopsParams(request);//参数
    String openUrl = request.getParameter("openUrl");
    String id = request.getParameter("id");
    if (request.getParameter("fetch") != null) {
      response.setHeader("Content-Type", "text/javascript");
      StringBuffer dirs = new StringBuffer("[");
      dirs.append("]");

      try {
        response.getWriter().write("updateSavePath( " + dirs.toString() + " );");
        response.getWriter().flush();
        response.getWriter().close();
        return;
      } catch (Exception e) {
        logger.error("UeditorImageUploadAction error", e);
        return;
      }
    }

    LoginUser loginUser = getLoginUser(request);
    String subImgDir = loginUser.getMemberId();

    if (StringUtil.isBlank(subImgDir)) {
      subImgDir = "m3";
    }

    String ufFileName = request.getParameter("fileName");
    String ufFileContentType = request.getParameter("ufFileContentType");
    String ufPath = request.getParameter("ufPath");
    try {
      String picUrl = "";
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      // 获得文件：
      MultipartFile uf = multipartRequest.getFile("file");
      if (uf != null) {

        InputStream fis = uf.getInputStream();
        SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
        Date currentTime = new Date();
        String postName = ".jpg";

        if (StringUtil.isNotBlank(ufFileName) && -1 != ufFileName.lastIndexOf(".")) {
          postName = ufFileName.substring(ufFileName.lastIndexOf("."));
        }

        String subcontextPath = dataFormat.format(currentTime) + postName;
        String contextPath = subcontextPath;

        byte bt[] = new byte[fis.available()];
        fis.read(bt);

        if (!imageYunService
            .writeFile(BopsConstants.IMG_MANAGER_PRE_ROOT_URL + subImgDir + "/" + contextPath, bt, true)) {
          logger.error("upYunService error" + imageYunService.getOutputDir());
        }
        picUrl = "http://" + params.get("imageDomain") + "/" + BopsConstants.IMG_MANAGER_PRE_URL + subImgDir + "/"
            + contextPath;
      }
      Picture picture = new Picture();
      if (!"".equals(id)) {
        picture = pictureService.getPicture(Long.valueOf(id));
      }
      if (!"".equals(picUrl)) {
        picture.setPicUrl(picUrl);
      }
      if (!"".equals(openUrl)) {
        picture.setOpenUrl(openUrl);
      }
      if (!"".equals(id)) {
        pictureService.update(picture);
      } else {
        pictureService.insert(picture);
      }
      response.sendRedirect("/bops/sys/banner/banner.htm");
      return;
    } catch (Exception e) {
      logger.error("UeditorImageUploadAction error", e);

    }
    try {
      response.getWriter().write(
          "{'original':'" + ufFileName + "','url':'','title':'" + ufFileName + "','state':'"
              + "\\u672a\\u77e5\\u9519\\u8bef" + "'}");
    } catch (Exception e) {
      logger.error("UeditorImageUploadAction error", e);

    }
    return;

  }

}
